#include "TextCapture.h"
#include <QTimer>
#include <QDebug>
#include <QApplication>
#include <QClipboard>

// 静态成员初始化
HHOOK TextCapture::m_mouseHook = nullptr;
bool TextCapture::m_isDragging = false;
TextCapture* TextCapture::m_receiver = nullptr;
POINT TextCapture::m_dragStartPos = {0, 0};

TextCapture::TextCapture(QObject* parent) : QObject(parent) {
    m_receiver = this;
    // 安装全局鼠标钩子
    m_mouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseProc, GetModuleHandle(nullptr), 0);
    if (!m_mouseHook) {
        qWarning() << "Failed to install mouse hook! Error:" << GetLastError();
    }
}

TextCapture::~TextCapture() {
    if (m_mouseHook) {
        UnhookWindowsHookEx(m_mouseHook);
        m_mouseHook = nullptr;
    }
}

// 鼠标钩子回调
LRESULT CALLBACK TextCapture::MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode >= 0) {
        auto* mouseInfo = reinterpret_cast<MSLLHOOKSTRUCT*>(lParam);
        switch (wParam) {
            case WM_LBUTTONDOWN:
                m_isDragging = true;  // 开始拖动
                m_dragStartPos = mouseInfo->pt;  // 记录拖动起始位置
                break;
            case WM_MOUSEMOVE:
                if (m_isDragging) {
                    // 检查拖动范围（避免误触发）
                    if (abs(mouseInfo->pt.x - m_dragStartPos.x) > 5 || 
                        abs(mouseInfo->pt.y - m_dragStartPos.y) > 5) {
                        // 拖动范围大于 5 像素，认为是有效拖动
                    }
                }
                break;
            case WM_LBUTTONUP:
                if (m_isDragging) {
                    m_isDragging = false;
                    // 检查拖动范围（避免误触发）
                    if (abs(mouseInfo->pt.x - m_dragStartPos.x) > 5 || 
                        abs(mouseInfo->pt.y - m_dragStartPos.y) > 5) {
                        // 模拟 Ctrl+C 复制选中文字到剪贴板
                        keybd_event(VK_CONTROL, 0, 0, 0);
                        keybd_event('C', 0, 0, 0);
                        keybd_event('C', 0, KEYEVENTF_KEYUP, 0);
                        keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);

                        // 延迟读取剪贴板内容（确保更新完成）
                        QTimer::singleShot(50, m_receiver, []() {
                            if (QClipboard* clipboard = QApplication::clipboard()) {
                                QString text = clipboard->text();
                                if (!text.isEmpty()) {
                                    emit m_receiver->textCaptured(text);
                                    clipboard->clear();  // 清空剪贴板避免残留
                                }
                            }
                        });
                    }
                }
                break;
        }
    }
    return CallNextHookEx(m_mouseHook, nCode, wParam, lParam);
}